package com.bidevalution.business.job;

import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeSectionParameter;
import com.bidevalution.dao.entity.BeSectionStepJob;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.util.StringUtil;
import com.google.common.collect.Maps;
import com.qtp.core.util.OConvertUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @description: 标记计算基准价去高去低的单位
 * @author: xiayf
 * @date: 2019-12-29 11:03
 */
@Log4j2
public class SaveRemoveLimitJob implements StepJobJdbcFactory {

    private JdbcTemplateService jdbcTemplateService;

    @Override
    public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode, String expertId, String layoutCode) throws Exception {
        try {
            //处理配置参数 格式:参数1(大于或大于等于家数),参数2(最低比例基数),参数3(最高比例基数),参数4(比较符号,>或>=)
            String[] paramArray = beSectionStepJob.getJobContent().split(",");
            if(paramArray.length<Constants.FOUR){
                throw new Exception("报错方法：SaveRemoveLimitJob，原因评标：方法任务参数配置缺失！");
            }
            Map<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("sectionStepId", beSectionStepJob.getSectionStepId());
            paramMap.put("sectionId", beSectionStepJob.getSectionId());
            //重置此项目被标记的单位
            jdbcTemplateService.update(" UPDATE be_section_enterprise SET is_one_flag=0 WHERE section_id=:sectionId AND is_one_flag=1 ", paramMap);
            StringBuilder sb = new StringBuilder();
            sb.append(" SELECT a.enterprise_id enterprise_id ");
            sb.append(" FROM be_evalution_summary a ");
            sb.append(" LEFT JOIN td_bidinfo b ON a.enterprise_id = b.enterprise_id ");
            sb.append(" WHERE a.section_step_id=:sectionStepId AND a.is_passed=1 and a.is_del=0 ");
            sb.append(" ORDER BY b.biin_Total ASC ");
            List<Map<String, Object>> dataList = jdbcTemplateService.selectForList(sb.toString(), paramMap);
            Map<String, String> sectionParameterMap = Maps.newHashMap();
            RowMapper<BeSectionParameter> rm = BeanPropertyRowMapper.newInstance(BeSectionParameter.class);
            List<BeSectionParameter> beSectionParameterList = jdbcTemplateService
                    .selectForList("SELECT param_id,param_value FROM be_section_parameter WHERE section_id=:sectionId",
                            paramMap, rm);
            //获取评标参数
            if (beSectionParameterList == null || beSectionParameterList.isEmpty()) {
                throw new Exception("*******没有查询到评标参数********");
            }
            for (BeSectionParameter beSectionParameter : beSectionParameterList) {
                sectionParameterMap.put(beSectionParameter.getParamId(), beSectionParameter.getParamValue());
            }
            String countStr = paramArray[0];
            //判断传入参数是否是数字
            if (!StringUtil.isNum(countStr)) {
                countStr = sectionParameterMap.get(paramArray[0]);
            }
            int count = OConvertUtils.getInt(countStr);
            if (">".equals(paramArray[3])) {
                count += 1;
            }
            if (dataList.size() >= count) {
                //去除最低家数
                Integer minLimit = 0;
                //去除最高家数
                Integer maxLimit = 0;
                if (StringUtil.isNum(paramArray[1]) && StringUtil.isNum(paramArray[2])) {
                    minLimit = new BigDecimal(paramArray[1]).multiply(new BigDecimal(dataList.size())).setScale(Constants.ZERO, BigDecimal.ROUND_HALF_UP).intValue();
                    maxLimit = new BigDecimal(paramArray[2]).multiply(new BigDecimal(dataList.size())).setScale(Constants.ZERO, BigDecimal.ROUND_HALF_UP).intValue();
                } else {
                    minLimit = new BigDecimal(sectionParameterMap.get(paramArray[1])).multiply(new BigDecimal(dataList.size())).divide(new BigDecimal("100"), Constants.ZERO, BigDecimal.ROUND_HALF_UP).intValue();
                    maxLimit = new BigDecimal(sectionParameterMap.get(paramArray[2])).multiply(new BigDecimal(dataList.size())).divide(new BigDecimal("100"), Constants.ZERO, BigDecimal.ROUND_HALF_UP).intValue();
                }
                if (dataList.size() >= (minLimit + maxLimit)) {
                    sb.setLength(0);
                    sb.append(" UPDATE be_section_enterprise SET is_one_flag=1 WHERE seq_id IN (");
                    for (int i = 0; i < minLimit; i++) {
                        if (i != 0) {
                            sb.append(",");
                        }
                        sb.append("'").append(dataList.get(0).get("enterprise_id")).append("'");
                        dataList.remove(0);
                    }
                    for (int i = 0; i < maxLimit; i++) {
                        sb.append(",").append("'").append(dataList.get(dataList.size() - 1).get("enterprise_id")).append("'");
                        dataList.remove(dataList.size() - 1);
                    }
                    sb.append(")");
                    jdbcTemplateService.update(sb.toString(), paramMap);
                }
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    @Override
    public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
        this.jdbcTemplateService = jdbcTemplateService;
    }
}
